package com.ptu.server;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.ptu.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OSSService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private OSSConfig ossConfig;

    /**
     * 从OSS URL中提取文件名
     * @param url OSS文件URL
     * @return 文件名
     */
    private String getFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        // 获取最后一个斜杠后面的内容
        String[] parts = url.split("/");
        if (parts.length > 0) {
            return "avatars/" + parts[parts.length - 1];
        }
        return null;
    }

    /**
     * 删除OSS中的文件
     * @param objectName 文件名（包含路径）
     */
    private void deleteFile(String objectName) {
        try {
            ossClient.deleteObject(ossConfig.getBucketName(), objectName);
        } catch (Exception e) {
            // 删除失败时记录日志，但不影响新文件上传
            System.out.println("删除旧头像失败: " + e.getMessage());
        }
    }

    /**
     * 上传文件到OSS
     * @param file 文件
     * @param oldAvatarUrl 用户旧头像URL（如果有）
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file, String oldAvatarUrl) throws IOException {
        // 如果存在旧头像，先删除
        if (oldAvatarUrl != null && oldAvatarUrl.contains(ossConfig.getBucketName())) {
            String oldFileName = getFileNameFromUrl(oldAvatarUrl);
            if (oldFileName != null) {
                deleteFile(oldFileName);
            }
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = "avatars/" + UUID.randomUUID().toString() + extension;

        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(),
                fileName,
                file.getInputStream()
        );

        // 上传文件
        ossClient.putObject(putObjectRequest);

        System.out.println("上传成功");
        // 返回文件访问路径
        return "https://" + ossConfig.getBucketName() + "." +
                ossConfig.getEndpoint().replace("http://", "") + "/" +
                fileName;
    }

    /**
     * 上传商品图片到OSS
     * @param file 文件
     * @param folder 存储文件夹
     * @return 文件访问URL
     */
    public String uploadProductImage(MultipartFile file, String folder) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = folder + UUID.randomUUID().toString() + extension;

        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(),
                fileName,
                file.getInputStream()
        );

        // 上传文件
        ossClient.putObject(putObjectRequest);
        System.out.println("上传成功");

        // 返回文件访问路径
        return "https://" + ossConfig.getBucketName() + "." +
                ossConfig.getEndpoint().replace("http://", "") + "/" +
                fileName;
    }


    public String uploadCommentImage(MultipartFile file, String folder) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = folder + UUID.randomUUID().toString() + extension;

        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(),
                fileName,
                file.getInputStream()
        );

        // 上传文件
        ossClient.putObject(putObjectRequest);
        System.out.println("上传成功");

        // 返回文件访问路径
        return "https://" + ossConfig.getBucketName() + "." +
                ossConfig.getEndpoint().replace("http://", "") + "/" +
                fileName;
    }

    /**
     * 上传秒杀商品图片到OSS
     * @param file 文件
     * @param folder 存储文件夹
     * @return 文件访问URL
     */
    public String uploadSeckillProductImage(MultipartFile file, String folder) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = folder + UUID.randomUUID().toString() + extension;

        // 创建上传请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfig.getBucketName(),
                fileName,
                file.getInputStream()
        );

        // 上传文件
        ossClient.putObject(putObjectRequest);
        System.out.println("上传成功");

        // 返回文件访问路径
        return "https://" + ossConfig.getBucketName() + "." +
                ossConfig.getEndpoint().replace("http://", "") + "/" +
                fileName;
    }


}
